package com.innovation.ic.cc.base.service.cc.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.b1b.framework.util.XmlUtil;
import com.innovation.ic.cc.base.handler.cc.ModelHandler;
import com.innovation.ic.cc.base.mapper.cc.PostSaleMapper;
import com.innovation.ic.cc.base.model.cc.PostSale;
import com.innovation.ic.cc.base.pojo.constant.PostSaleConstants;
import com.innovation.ic.cc.base.pojo.constant.handler.RedisStorage;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.service.ServiceHelper;
import com.innovation.ic.cc.base.service.cc.PostSaleService;
import com.innovation.ic.cc.base.vo.PostSaleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class PostSaleServiceImpl extends ServiceImpl<PostSaleMapper, PostSale> implements PostSaleService {

    @Resource
    private ServiceHelper serviceHelper;

    @Resource
    protected ModelHandler modelHandler;

    //将post_sale表的数据导入到redis
    public void initPostSaleData() {
        List<PostSale> postSales = baseMapper.selectList(null);//获取所有售后管理数据
        if (postSales.size() != 0) {
            String keyDesc = RedisStorage.TABLE + RedisStorage.POST_SALE + RedisStorage.APPLICATION_DATE_DESC;
            // 删除旧的数据
            Boolean deleteResult = serviceHelper.getRedisManager().del(keyDesc);
            if (deleteResult) {
                log.info("删除[{}]开头的数据成功", RedisStorage.TABLE + RedisStorage.POST_SALE + RedisStorage.APPLICATION_DATE_DESC);
            }
            for (PostSale postSale : postSales) {
                String value = modelHandler.brandToXmlStorageString(postSale);
                serviceHelper.getRedisManager().zAdd(keyDesc, value, postSale.getApplicationDate().getTime());
            }
        }
    }

    /**
     * 分页展示售后管理数据
     *
     * @param postSaleVo
     * @return
     */
    public ServiceResult<PageInfo<PostSale>> pagePostSale(PostSaleVo postSaleVo) {
        String keyDesc = RedisStorage.TABLE + RedisStorage.POST_SALE + RedisStorage.APPLICATION_DATE_DESC;
        PostSale postSale = new PostSale();
        if (postSaleVo.getStartData() != null) {//日期查询不为空
            if (StringUtils.isEmpty(postSaleVo.getModel()) && StringUtils.isEmpty(postSaleVo.getOrderNo()) && StringUtils.isEmpty(postSaleVo.getWaybillNumber()) && postSaleVo.getType() == null) {
                Set<String> strings = serviceHelper.getRedisManager().zRangeByScore(keyDesc, postSaleVo.getStartData().getTime(), postSaleVo.getCeaseData().getTime());
                List list = new ArrayList<>(strings);
                if (list.size() == 0) {
                    return null;
                } else {
                    return ServiceResult.ok(listPage(list, postSaleVo.getPageNo(), postSaleVo.getPageSize(), PostSaleConstants.TYPE_ONE, postSaleVo), "查询售后管理列表数据成功");
                }
            }
        }
        if (!StringUtils.isEmpty(postSaleVo.getModel())) {//型号是否为空
            postSale.setModel(postSaleVo.getModel());
        }
        if (!StringUtils.isEmpty(postSaleVo.getOrderNo())) {//订单项是否为空
            postSale.setOrderNo(postSaleVo.getOrderNo());
        }
        if (!StringUtils.isEmpty(postSaleVo.getWaybillNumber())) {//运单号是否为空
            postSale.setWaybillNumber(postSaleVo.getWaybillNumber());
        }
        if (postSaleVo.getType() != null) {//类型是否为空
            postSale.setType(postSaleVo.getType());
        }
        String pattern = modelHandler.brandToXmlFilterString(postSale, true);
        List list = serviceHelper.getRedisManager().pageSort(keyDesc, pattern, false);
        if (list.size() == 0) {
            return null;
        } else {
            if (postSaleVo.getStartData() != null) {
                return ServiceResult.ok(listPage(list, postSaleVo.getPageNo(), postSaleVo.getPageSize(), PostSaleConstants.TYPE_TWO, postSaleVo), "查询售后管理列表数据成功");
            } else {
                return ServiceResult.ok(listPage(list, postSaleVo.getPageNo(), postSaleVo.getPageSize(), PostSaleConstants.TYPE, postSaleVo), "查询售后管理列表数据成功");
            }

        }
    }

    /**
     * 获取格式化数据
     *
     * @param list
     * @param currentPage
     * @param pageSize
     * @return
     */
    public PageInfo<PostSale> listPage(List<String> list, int currentPage, int pageSize, Integer type, PostSaleVo postSaleVo) {
        PageInfo<PostSale> pageInfo = new PageInfo<>();
        //list总数
        int totalCount = list.size();
        //总页数
        int pageCount = 0;
        List<String> subyList = null;
        int m = totalCount % pageSize;
        if (m > 0) {
            pageCount = totalCount / pageSize + 1;
        } else {
            pageCount = totalCount / pageSize;
        }

        if (m == 0) {
            subyList = list.subList((currentPage - 1) * pageSize, pageSize * (currentPage));
        } else {
            if (currentPage == pageCount) {
                subyList = list.subList((currentPage - 1) * pageSize, totalCount);
            }
            if (currentPage < pageCount) {
                subyList = list.subList((currentPage - 1) * pageSize, pageSize * (currentPage));
            }
        }
        if (currentPage > pageCount) {
            return null;
        }

        List<PostSale> postSaleArrayList = new ArrayList<>();
        if (null != subyList && subyList.size() > 0) {
            for (int i = 0; i < subyList.size(); i++) {
                String xmlString = (String) subyList.get(i);
                String jsonString = XmlUtil.xmlStringToJSON(xmlString).toString();
                postSaleArrayList.add(JSON.parseObject(jsonString, PostSale.class));
            }
        }
        List<PostSale> postSales = new ArrayList<>();
        if (type == PostSaleConstants.TYPE_ONE) {//只有时间筛选情况
            //降序
            postSaleArrayList.sort(Comparator.comparing(PostSale::getApplicationDate).reversed());
        }
        if (type == PostSaleConstants.TYPE_TWO) {
            for (PostSale postSale : postSaleArrayList) {
                if (postSale.getApplicationDate().getTime() >= postSaleVo.getStartData().getTime() && postSale.getApplicationDate().getTime() <= postSaleVo.getCeaseData().getTime()) {
                    postSales.add(postSale);
                }
            }
            //封装返回pageInfo
            pageInfo.setTotal(postSales.size());
            pageInfo.setPages(pageCount);
            pageInfo.setPageNum(currentPage);
            pageInfo.setPageSize(pageSize);
            pageInfo.setList(postSales);
            pageInfo.setSize(postSales.size());
            pageInfo.calcByNavigatePages(8);
            return pageInfo;
        }
        //封装返回pageInfo
        pageInfo.setTotal(totalCount);
        pageInfo.setPages(pageCount);
        pageInfo.setPageNum(currentPage);
        pageInfo.setPageSize(pageSize);
        pageInfo.setList(postSaleArrayList);
        pageInfo.setSize(postSaleArrayList.size());
        pageInfo.calcByNavigatePages(8);
        return pageInfo;
    }
}
